<template>
  <div class="repair-form-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" class="search-form">
        <el-form-item label="维修单编号">
          <el-input v-model="searchParams.repairCode" placeholder="请输入维修单编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="维修单名称">
          <el-input v-model="searchParams.repairName" placeholder="请输入维修单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="设备编码">
          <el-input v-model="searchParams.equipmentCode" placeholder="请输入设备编码" clearable></el-input>
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input v-model="searchParams.equipmentName" placeholder="请输入设备名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="维修结果">
          <el-input
            v-model="searchParams.repairResult"
            placeholder="请输入维修结果"
            clearable
            style="width: 120px;"
          ></el-input>
        </el-form-item>
        <el-form-item label="单据状态">
          <el-select v-model="searchParams.status" placeholder="请选择单据状态" clearable style="width: 120px;">
            <el-option 
              v-for="item in statusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon>
              <Search />
            </el-icon>查询
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <div class="table-header">
        <el-button type="danger" @click="handleBatchDelete" :disabled="selectedIds.length === 0">
          <el-icon>
            <Delete />
          </el-icon>删除
        </el-button>
      </div>

      <!-- 表格 -->
      <el-table
        ref="repairFormTable"
        :data="tableData"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        v-loading="loading"
        highlight-current-row
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="repairCode" label="维修单编号" width="120"></el-table-column>
        <el-table-column prop="repairName" label="维修单名称" width="120"></el-table-column>
        <el-table-column prop="equipmentCode" label="设备编码" width="120"></el-table-column>
        <el-table-column prop="checkMan" label="验收人员" width="100"></el-table-column>
        <el-table-column prop="checkDate" label="验收日期" width="120"></el-table-column>
        <el-table-column prop="repairDate" label="报修日期" width="120"></el-table-column>
        <el-table-column prop="finshDate" label="维修完成日期" width="120"></el-table-column>
        <el-table-column prop="repairResult" label="维修结果" width="100"></el-table-column>
        <el-table-column prop="repairer" label="维修人员" width="100"></el-table-column>
        <el-table-column prop="status" label="单据状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 4 ? 'success' : getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="descs" label="故障描述" width="150"></el-table-column>
        <el-table-column label="操作" fixed="right" width="180" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              修改
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <span class="total-text">共 {{ total }} 条</span>
        <el-select v-model="pageSize" placeholder="条/页" style="width: 100px">
          <el-option :value="10" label="10条/页"></el-option>
          <el-option :value="20" label="20条/页"></el-option>
          <el-option :value="50" label="50条/页"></el-option>
          <el-option :value="100" label="100条/页"></el-option>
        </el-select>
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        >
        </el-pagination>
        <span class="page-info">前往 <el-input v-model="goToPage" style="width: 50px;"></el-input> 页</span>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑维修单"
      width="650px"
      :close-on-click-modal="false"
      :show-close="true"
      @close="resetForm"
      center
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
        class="repair-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修单编号" prop="repairCode" required>
              <el-input v-model="formData.repairCode" placeholder="系统自动生成" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修单名称" prop="repairName" required>
              <el-input v-model="formData.repairName" placeholder="请输入维修单名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="设备" prop="equipmentCode" required>
              <el-input v-model="formData.equipmentCode"  disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报修日期" prop="repairDate" required>
              <el-date-picker
                v-model="formData.repairDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修人员" prop="repairer">
              <el-select 
                v-model="formData.repairer" 
                placeholder="请选择维修人员"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in personnelOptions"
                  :key="item.user_Id"
                  :label="item.userTrueName"
                  :value="item.userTrueName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="维修完成日期" prop="finshDate">
              <el-date-picker
                v-model="formData.finshDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="验收人员" prop="checkMan">
              <el-select 
                v-model="formData.checkMan" 
                placeholder="请选择验收人员"
                filterable
                style="width: 100%"
              >
                <el-option
                  v-for="item in personnelOptions"
                  :key="item.user_Id"
                  :label="item.userTrueName"
                  :value="item.userTrueName"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收日期" prop="checkDate">
              <el-date-picker
                v-model="formData.checkDate"
                type="datetime"
                placeholder="选择日期时间"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="维修结果" prop="repairResult">
              <el-input
                v-model="formData.repairResult"
                placeholder="请输入维修结果"
                style="width: 100%"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单据状态" prop="status">
              <el-select v-model="formData.status" placeholder="请选择单据状态" style="width: 100%">
                <el-option 
                  v-for="item in statusOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="故障描述" prop="descs">
          <el-input
            v-model="formData.descs"
            type="textarea"
            :rows="3"
            placeholder="请输入故障描述"
          ></el-input>
        </el-form-item>

        <el-form-item label="维修内容" prop="repairContent">
          <el-input
            v-model="formData.repairContent"
            type="textarea"
            :rows="3"
            placeholder="请输入维修内容"
          ></el-input>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="cancel-btn">取 消</el-button>
          <el-button type="primary" @click="submitForm" class="confirm-btn">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import http from '@/api/http';
import { Search, Delete } from '@element-plus/icons-vue';
import { formatDate } from '@/utils/date';

// API基础路径
const baseApiUrl = '/api/RepairForm';

// 加载状态
const loading = ref(false);

// 表格数据
const tableData = ref([]);

// 选中行IDs
const selectedIds = ref([]);

// 分页参数
const total = ref(0);
const pageSize = ref(10);
const currentPage = ref(1);
const goToPage = ref(1);

// 搜索参数
const searchParams = reactive({
  repairCode: '',
  repairName: '',
  equipmentCode: '',
  equipmentName: '',
  repairResult: '',
  status: null
});

// 表单对话框
const dialogVisible = ref(false);
const formRef = ref(null);

// 表格引用
const repairFormTable = ref(null);

// 设备选项
const equipmentOptions = ref([]);

// 人员选项
const personnelOptions = ref([]);

// 表单数据
const formData = reactive({
  id: 0,
  repairCode: '',
  repairName: '',
  equipmentCode: '',
  equipmentName: '',
  repairDate: '',
  repairer: '',
  finshDate: '',
  checkMan: '',
  checkDate: '',
  repairResult: '',
  status: 0, // 0表示草稿，739表示已完成
  descs: '',
  repairContent: '',
  remark: ''
});

// 表单规则
const formRules = reactive({
  repairName: [
    { required: true, message: '请输入维修单名称', trigger: 'blur' }
  ],
  repairDate: [
    { required: true, message: '请选择报修日期', trigger: 'change' }
  ]
});

// 单据状态选项
const statusOptions = [
  { label: '草稿', value: 0 },
  { label: '待维修', value: 1 },
  { label: '维修中', value: 2 },
  { label: '待验收', value: 3 },
  { label: '已完成', value: 4 }
];

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true;
    
    // 构建查询参数
    const params = {
      pageIndex: currentPage.value,
      pageSize: pageSize.value,
      repairCode: searchParams.repairCode,
      repairName: searchParams.repairName,
      equipmentCode: searchParams.equipmentCode,
      equipmentName: searchParams.equipmentName,
      repairResult: searchParams.repairResult,
      status: searchParams.status
    };
    
    // API调用 - 使用POST请求获取维修单列表
    const response = await http.post(`${baseApiUrl}/GetRepairForm`, params);
    
    if (response && response.status === 0) {
      // 根据截图显示，响应数据直接包含rows和total
      tableData.value = response.rows || [];
      total.value = response.total || 0;
    } else {
      ElMessage.error(response?.msg || '获取数据失败');
      tableData.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取数据出错:', error);
    ElMessage.error('获取数据失败，请稍后再试');
    tableData.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchParams.repairCode = '';
  searchParams.repairName = '';
  searchParams.equipmentCode = '';
  searchParams.equipmentName = '';
  searchParams.repairResult = '';
  searchParams.status = null;
  currentPage.value = 1;
  fetchData();
};

// 表格选择变化
const handleSelectionChange = (rows) => {
  selectedIds.value = rows.map(row => row.id).filter(Boolean);
};

// 编辑
const handleEdit = (row) => {
  console.log(row);
  
  // 映射API返回的字段到表单字段
  Object.keys(formData).forEach(key => {
    if (key in row) {
      formData[key] = row[key];
    }
  });
  
  dialogVisible.value = true;
  
  // 加载设备和人员选项
  loadPersonnelOptions();
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  
  Object.assign(formData, {
    id: 0,
    repairCode: '',
    repairName: '',
    equipmentId: '',
    equipmentCode: '',
    equipmentName: '',
    repairDate: '',
    repairer: '',
    finshDate: '',
    checkMan: '',
    checkDate: '',
    repairResult: '',
    status: 0, // 默认为草稿状态
    descs: '',
    repairContent: '',
    remark: ''
  });
};

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate();
    
    loading.value = true;
    
    // 准备提交的数据
    const submitData = { ...formData };
    
    // 格式化日期字段
    if (submitData.repairDate) {
      submitData.repairDate = formatDate(submitData.repairDate);
    }
    if (submitData.finshDate) {
      submitData.finshDate = formatDate(submitData.finshDate);
    }
    if (submitData.checkDate) {
      submitData.checkDate = formatDate(submitData.checkDate);
    }
    // 更新维修单
    const response = await http.post(`${baseApiUrl}/UpdRepairForm`, submitData);
    
    if (response) {
      ElMessage.success('修改成功');
      dialogVisible.value = false;
      fetchData();
    } else {
      ElMessage.error(response?.message || '操作失败');
    }
  } catch (error) {
    console.error('提交表单出错:', error);
    ElMessage.error('操作失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除此维修单吗？', '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 删除单个维修单
    const response = await http.post(`${baseApiUrl}/DelRepairForm?ids=${id}`);
    
    if (response && response.status) {
      ElMessage.success('删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除出错:', error);
      ElMessage.error('删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条记录');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确认删除选中的 ${selectedIds.value.length} 条记录？`, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    loading.value = true;
    
    // 批量删除维修单
    const ids = selectedIds.value.join(',');
    const response = await http.post(`${baseApiUrl}/DelRepairForm?ids=${ids}`);
    
    if (response && response.status) {
      ElMessage.success('批量删除成功');
      fetchData();
    } else {
      ElMessage.error(response?.message || '批量删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除出错:', error);
      ElMessage.error('批量删除失败，请稍后再试');
    }
  } finally {
    loading.value = false;
  }
};

// 分页 - 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 分页 - 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  fetchData();
};

// 加载设备选项
const loadEquipmentOptions = async () => {
  try {
    const response = await http.get('/api/Equipment/GetEquipmentList');
    if (response && response.status) {
      equipmentOptions.value = response.data || [];
    }
  } catch (error) {
    console.error('获取设备选项出错:', error);
  }
};

// 搜索设备
const searchEquipment = async (query) => {
  if (query) {
    try {
      const response = await http.get(`/api/Equipment/GetEquipmentList?keyword=${query}`);
      if (response && response.status) {
        equipmentOptions.value = response.data || [];
      }
    } catch (error) {
      console.error('搜索设备出错:', error);
    }
  }
};

// 处理设备变化
const handleEquipmentChange = (value) => {
  if (value) {
    const equipment = equipmentOptions.value.find(item => item.id === value);
    if (equipment) {
      formData.equipmentCode = equipment.equipmentCode;
      formData.equipmentName = equipment.equipmentName;
    }
  } else {
    formData.equipmentCode = '';
    formData.equipmentName = '';
  }
};

// 加载人员选项
const loadPersonnelOptions = async () => {
  try {
    const response = await http.get('/api/MeadingReport/GetUserList');
    console.log(response);
    
    if (response && response.data) {
      personnelOptions.value = response.data || [];
    } else {
      // 如果没有API或者API不可用，使用模拟数据
      personnelOptions.value = [
        { user_Id: 1, userTrueName: '张三' },
        { user_Id: 2, userTrueName: '李四' },
        { user_Id: 3, userTrueName: '王五' }
      ];
    }
  } catch (error) {
    console.error('获取人员选项出错:', error);
    // 使用模拟数据
    personnelOptions.value = [
      { user_Id: 1, userTrueName: '张三' },
      { user_Id: 2, userTrueName: '李四' },
      { user_Id: 3, userTrueName: '王五' }
    ];
  }
};

// 状态映射
const getStatusText = (status) => {
  const statusMap = {
    0: '草稿',
    1: '待维修',
    2: '维修中',
    3: '待验收',
    4: '已完成'
  }
  return statusMap[status] || '未知状态'
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'info',
    1: 'warning',
    2: 'primary',
    3: 'warning',
    4: 'success'
  }
  return typeMap[status] || ''
}

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.repair-form-container {
  padding: 20px;
}

.search-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-container {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.total-text {
  margin-right: auto;
  color: #606266;
}

.page-info {
  display: flex;
  align-items: center;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.repair-form :deep(.el-form-item__label) {
  font-weight: normal;
  color: #606266;
}

.repair-form :deep(.el-form-item__label::before) {
  color: #f56c6c;
}

.cancel-btn {
  width: 80px;
}

.confirm-btn {
  width: 80px;
  background-color: #409eff;
}

:deep(.el-dialog__header) {
  margin-right: 0;
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  padding: 15px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0;
}

:deep(.el-dialog__footer) {
  padding: 10px 20px 20px;
  text-align: center;
}

:deep(.el-dialog__headerbtn) {
  top: 15px;
}
</style>
